<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use app\common\model\goods\GoodsSpecGroupModel;
use Exception;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 分类管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Category extends Backend
{

    /**
     * @var \app\common\model\Category
     */
    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage','getCategoryList', 'selectpagetree'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\common\model\Category');

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $typeList = CategoryModel::getTypeList();
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("typeList", $typeList);
        $this->view->assign("parentList", $categorydata);
        $this->assignconfig('typeList', $typeList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            if ($this->request->request('keyValue')) {
                return $this->selectpage();
            }

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isPost()) {
//            $this->token();
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        Db::startTrans();
        try {

            $pinyin = new \Overtrue\Pinyin\Pinyin();
            $first = $pinyin->abbr($params['name']);
            $params['cate_sn'] = $first . time();

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\common\model\Category::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child or itself'));
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 搜索下拉列表
     */
    public function getCategoryList()
    {
        $where['status'] = 1;
//        $result = $this->model->where($where)->select();
        $result = $this->categorylist;
        $searchlist = [];
        foreach ($result as $key => $value) {
            $searchlist[] = ['id' => $value['id'], 'name' => $value['name']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }



    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }



    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpagetree()
    {
        $search = $this->request->request("search");
        $name = $this->request->request("name");
        $diyname = $this->request->request("diyname");

        if ($this->request->request('keyValue')) {
            return $this->selectpage();
        }

        $search = $search??$name??$diyname;

        //构造父类select列表选项数据
        $list = [];

        if(!empty($search)){
            $search_data = $this->model
                ->where('name', 'like', "%$search%")
                ->column('id');
            if($search_data){
                $pid_arr = [];
                foreach ($search_data as $row){
                    \app\common\model\Category::getCategoryPid($row,$pid);
                    if(!in_array($pid,$pid_arr)){
                        $pid_arr[] = $pid;
                        // 取出包含自己的所有子节点
                        $childrenList = Tree::instance()->init($this->categorylist, 'pid')->getChildren($pid, true);
                        $list = array_merge($list, Tree::instance()->getTreeList($childrenList));
                    }
                }
            }
        }else{
            $list = $this->categorylist;
        }

        foreach ($list as $key => $val){
            $list[$key]['name'] = str_replace('&nbsp;','',$val['name']);
//            $list[$key]['diyname'] = trim(str_replace($val['spacer'],'',$val['name']));
            // 获取关联属性
            $id = $val['id'];
            $FIND_IN_SET = "FIND_IN_SET('$id',`admin_cate_ids`)";
            $list[$key]['diyname'] = implode('/',Tree::instance()->getParentsName($val['id'],true));
            $spec_group = GoodsSpecGroupModel::whereRaw($FIND_IN_SET)->value('goods_spec_type');
//            属性分类:sale=销售属性,key=关键属性,nokey=非关键属性,goods=商品属性
            $goods_spec_type = ['sale' => '销售属性','key' => '关键属性','nokey' => '非关键属性','goods' => '商品属性'];
            $list[$key]['diyname'] = empty($spec_group)?$list[$key]['diyname']: "($goods_spec_type[$spec_group])" . $list[$key]['diyname'];
        }

        $total = count($list);
        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }
}
